import { Image, InfiniteScroll, List } from "antd-mobile";
// mock数据
import { useEffect, useState } from "react";
import { getBookListApi, BookRes } from "@/apis";
import { useNavigate } from "react-router-dom";

type Props = {
  channelId: string;
};

const ItemList = (props: Props) => {
  // 接收频道id
  const { channelId } = props;

  // 存放文档状态
  const [bookRes, setBookRes] = useState<BookRes>({
    results: [],
    pre_timestamp: "" + new Date().getTime(),
  });

  // 封装请求文章列表方法
  const getBookList = async () => {
    const res = await getBookListApi({
      channel_id: channelId,
      timestamp: "" + new Date().getTime(),
    });
    setBookRes({
      results: res.data.data.results,
      pre_timestamp: res.data.data.pre_timestamp,
    });
  };

  // 每次频道id更改 重新请求一次
  useEffect(() => {
    getBookList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [channelId]);

  // 标记是否需要加载更多
  const [hasMore, setHasMore] = useState(true);

  // 加载更多
  const loadMore = async () => {
    console.log("加载更多");
    const res = await getBookListApi({
      channel_id: channelId,
      timestamp: bookRes.pre_timestamp,
    });

    setBookRes({
      results: [...bookRes.results, ...res.data.data.results],
      pre_timestamp: res.data.data.pre_timestamp,
    });
    // 停止监听
    if (res.data.data.results.length === 0) {
      setHasMore(false);
    }
  };

  const navigate = useNavigate()
  const goToDetail = (id: string) => {
    // 路由跳转
    navigate(`/detail?id=${id}`)
  }



  return (
    <>
      <List>
        {bookRes.results.map((item) => (
          <List.Item
            key={item.art_id}
            onClick={()=>goToDetail(item.art_id)}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
          >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>
  );
};

export default ItemList;
